package com.hx.app.leetcode.com.hx.twosum;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author hx 2022/7/3 10:33
 */
public class TwoSum {
    public static void main(String[] args) {
        Solution solution = new Solution();
        // int[] nums = {2, 7, 11, 15};
        // int target = 9;
        // int[] nums = {3,2,4};
        // int target = 6;
        int[] nums = {3, 3};
        int target = 6;
        int[] res = solution.twoSum(nums, target);
        System.out.println(Arrays.toString(res));
    }
}

class Solution {
    /**
     * 暴力解法1
     *
     * @param nums
     * @param target
     * @return
     */
    /*public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if ((nums[i] + nums[j]) == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return null;
    }*/

    /**
     * 暴力解法2
     *
     * @param nums
     * @param target
     * @return
     */
    /*public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int i = 0, j = i + 1;
        while (true) {
            if ((nums[i] + nums[j]) == target) {
                res[0] = i;
                res[1] = j;
                return res;
            }
            if (j < nums.length - 1) {
                j++;
            } else if (j == nums.length - 1) {
                i++;
                j = i + 1;
            }
            if ((i == nums.length - 1) && (j == nums.length)) {
                break;
            }
        }
        return null;
    }*/

    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> targetMap = new HashMap<>(16);
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            int value = target - nums[i];
            if (!targetMap.containsKey(value)) {
                targetMap.put(nums[i], i);
            } else {
                res[0] = targetMap.get(value);
                res[1] = i;
                return res;
            }
        }
        return res;
    }
}